package com.erik.lin.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Created by Erik on 2017/4/1.
 */
@Component
public class AppContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    /**
     * 当继承了ApplicationContextAware类之后，那么程序在调用
     * getBean(String)的时候会自动调用该方法，不用自己操作
     */

    private static DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public void setApplicationContext(
            org.springframework.context.ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext= applicationContext;
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext
                .getBeanFactory();
    }

    public static Object getBean(String beanName){
        return AppContext.applicationContext.getBean(beanName);
    }

    public static void registerBeanDefinition(String beanId, GenericBeanDefinition beanDefinition, String[] beanAlias){
        defaultListableBeanFactory.registerBeanDefinition(beanId,beanDefinition);
        for (int j = 0;beanAlias!=null && beanAlias.length>0 && j < beanAlias.length; j++) {
            defaultListableBeanFactory.registerAlias(beanId,beanAlias[j]);
        }
    }
}